<template>
  <div class="app-container">

    <!-- 课程信息表单 -->
    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
        </el-select>
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <el-form-item label="课程类别">
        <el-cascader v-model="subjectSelectIds" placeholder="试试搜索：java" :options="subjectList" :props="props"
          filterable>
        </el-cascader>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数" />
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <!-- 课程封面 -->
      <el-form-item label="课程封面">
        <el-upload class="cover-uploader" action="http://vcourse-file-1.oss-cn-hangzhou.aliyuncs.com" :show-file-list="false"
          :data="dataObj" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleError">
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元" /> 元
      </el-form-item>
    </el-form>
    <div style="text-align:center">
      <el-button :disabled="saveBtnDisabled" type="primary" @click="saveAndNext()">保存并下一步</el-button>
    </div>
  </div>
</template>

<script>
  import {
    saveCourseInfo,
    getCourseById,
    updateCourseInfoById
  } from '@/api/course'
  import {
    list
  } from '@/api/teacher'
  import {
    getNestedTreeList
  } from '@/api/subject'
  import {
      uploadPolicy,
      deleteAvatar
  } from '@/api/oss'
  import {
    getUUID
  } from '@/utils/myfun'
  import Tinymce from '@/components/Tinymce'

  export default {
    components: {
      Tinymce
    },
    data() {
      return {
        saveBtnDisabled: false, // 按钮是否禁用
        courseInfo: {
          cover: '',
          description: ''
        },
        // 讲师列表
        teacherList: [],
        // 课程分类列表
        subjectList: [],
        props: {
          value: 'id',
          label: 'title',
          children: 'children'
        },
        // 课程分类级联选择的id数组
        subjectSelectIds: [],
        // 文件上传请求的签名信息
        dataObj: {
          key: '',
          policy: '',
          OSSAccessKeyId: '',
          success_action_status: '',
          signature: ''
        }
      }
    },
    created() {
      this.getTeacherList()
      this.getSubjectList()
      // if (this.$route.name == "CourseInfoEdit"){
      //   this.$parent.courseId = this.$route.params.id
      // }
      if (this.$parent.courseId) {
        this.fetchCourseInfo()
      }
    },
    methods: {
      // 更新课程信息
      updateCourse() {
        if (this.subjectSelectIds.length == 0) {
          this.$message.warning("请选择课程分类再保存")
        } else {
          // 取出课程id数组对课程信息赋值
          this.courseInfo.subjectParentId = this.subjectSelectIds[0]
          this.courseInfo.subjectId = this.subjectSelectIds[this.subjectSelectIds.length - 1]
          updateCourseInfoById(this.courseInfo).then(response => {
            this.$message.success(response.message)
            this.$parent.active = 1
          })
        }
      },

      // 若有课程ID，回显数据
      fetchCourseInfo() {
        getCourseById(this.$parent.courseId).then(response => {
          this.courseInfo = response.data
          this.subjectSelectIds = [this.courseInfo.subjectParentId, this.courseInfo.subjectId]
        })
      },

      // 文件上传成功
      handleAvatarSuccess(res, file) {
        this.courseInfo.cover = this.dataObj.host + '/' + this.dataObj.key
        // 强制重新渲染
        this.$forceUpdate()
      },
      // 文件上传前校验
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 4;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
          return false
        } else {
          let dir = 'course-cover'
          let _self = this;
          // 请求签名(必须使用Promise，要不然dataObj无法及时绑定)
          return new Promise((resolve, reject) => {
            uploadPolicy(dir).then(response => {
              // 设置文件的完整路径
              _self.dataObj.key = response.data.dir + '/' + getUUID() + file.name
              _self.dataObj.policy = response.data.policy
              _self.dataObj.signature = response.data.signature
              _self.dataObj.OSSAccessKeyId = response.data.accessid
              _self.dataObj.dir = response.data.dir
              _self.dataObj.host = response.data.host
              _self.dataObj.success_action_status = '200'
              resolve(true)
            }).catch(err => {
              console.log(err)
              reject(false)
            })
          })
        }
      },
      // 文件上传失败(http)
      handleError(err, file) {
        console.log('文件上传失败')
        // 弹出成功提示
        this.$message.error(err)
      },

      // 查询讲师列表
      getTeacherList() {
        list().then(response => {
          this.teacherList = response.data
        })
      },

      // 查询课程分类
      getSubjectList() {
        getNestedTreeList().then(response => {
          this.subjectList = response.data
        })
      },

      // 保存并下一步
      saveAndNext() {
        this.saveBtnDisabled = true
        if (!this.$parent.courseId) {
          this.saveData()
        } else {
          this.updateCourse()
        }
      },

      saveData() {
        if (this.subjectSelectIds.length == 0) {
          this.$message.warning("请选择课程分类再保存")
        } else {
          // 取出课程id数组对课程信息赋值
          this.courseInfo.subjectParentId = this.subjectSelectIds[0]
          this.courseInfo.subjectId = this.subjectSelectIds[this.subjectSelectIds.length - 1]
          saveCourseInfo(this.courseInfo).then(response => {
            this.$message.success(response.message)
            // 返回课程ID
            this.$parent.courseId = response.data
            this.$parent.active = 1
          })
        }
      }
    }
  }
</script>

<style>
  .tinymce-container {
    position: relative;
    line-height: normal;
  }

  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .cover-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .cover-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 640px;
    height: 357px;
    line-height: 357px;
    text-align: center;
  }

  .cover-uploader img {
    width: 640px;
    height: 357px;
    display: block;
  }
</style>
